﻿create PROCEDURE Sync.SP_Villages_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @Villages_Temp TABLE 
		(
			VillageID UniqueIdentifier,
			[VillageName] nvarchar(50),
				[CenterID] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @Villages_Temp 
	   SELECT	Tbl.Col.value('VillageID[1]','uniqueidentifier') VillageID,
                Tbl.Col.value('VillageName[1]', 'nvarchar(50)') [VillageName],
Tbl.Col.value('CenterID[1]', 'uniqueidentifier') [CenterID],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/Villages') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[Villages] ([VillageID],[VillageName],[CenterID])
	SELECT t.[VillageID],t.[VillageName],t.[CenterID]
	FROM  @Villages_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.Villages_Tracking s
        WHERE t.VillageID = s.VillageID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[Villages]
	SET [Villages].[VillageName] = t.[VillageName],[Villages].[CenterID] = t.[CenterID] 
	FROM [dbo].[Villages] s JOIN @Villages_Temp t 
    ON t.VillageID = s.VillageID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.Villages_Tracking r
				  WHERE t.VillageID = r.VillageID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[Villages]
    FROM @Villages_Temp t JOIN [dbo].[Villages] s
    ON t.VillageID = s.VillageID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END





